<template>
  <div class="pharmacy-manage">
    <!-- 筛选栏 -->
    <el-form :inline="true" :model="searchForm" class="filter-form">
      <el-form-item label="药房类型">
        <el-select v-model="searchForm.pharmacyType" placeholder="请选择" style="width: 120px" clearable @change="debouncedFetchData">
          <el-option v-for="item in pharmacyTypes" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择" style="width: 120px" @change="debouncedFetchData">
          <el-option label="全部" :value="''" />
          <el-option label="启用" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
            @change="debouncedFetchData"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="handleAdd">+新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%; margin-top: 16px">
      <el-table-column prop="index" label="序号" width="60" align="center" />
      <!-- <el-table-column prop="pharmacyId" label="编号" width="80" align="center" /> -->
      <el-table-column prop="campusName" label="所属院区" width="100" align="center" />
      <el-table-column prop="pharmacyName" label="名称" align="center" />
      <el-table-column prop="pharmacyType" label="类型" align="center" />
      <el-table-column prop="location" label="地址" align="center" />
      <el-table-column prop="contactPhone" label="联系电话" align="center" />
      <el-table-column prop="manager" label="负责人" align="center" />
      <el-table-column prop="businessHours" label="营业时间" align="center" />
      <el-table-column prop="status" label="状态" width="80" align="center">
        <template slot-scope="scope">
          <span :class="scope.row.status === 1 ? 'status-enabled' : 'status-disabled'">
            {{ scope.row.status === 1 ? '启用' : '停用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleEdit(scope.row)">编辑</el-link>
          <el-link
              v-if="scope.row.status === 1"
              type="danger"
              style="margin-left: 8px"
              @click="handleChangeStatus(scope.row, 0)"
          >停用</el-link>
          <el-link
              v-else
              type="success"
              style="margin-left: 8px"
              @click="handleChangeStatus(scope.row, 1)"
          >启用</el-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-wrapper">
      <el-pagination
          background
          layout="prev, pager, next, sizes, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="pageNum"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          :page-sizes="[10, 20, 50, 100]"
      />
    </div>

    <!-- 编辑弹框 -->
    <el-dialog
        title="编辑药房"
        :visible.sync="editDialogVisible"
        width="500px"
    >
      <el-form :model="editForm" ref="editForm" label-width="100px" :rules="formRules">
        <el-form-item label="编号" prop="pharmacyId">
          <el-input v-model="editForm.pharmacyId" disabled></el-input>
        </el-form-item>
        <el-form-item label="所属院区" prop="campusId">
          <el-select v-model="editForm.campusId" placeholder="请选择院区">
            <el-option
                v-for="item in campusList"
                :key="item.campusId"
                :label="item.campusName"
                :value="item.campusId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="药房名称" prop="pharmacyName">
          <el-input v-model="editForm.pharmacyName"></el-input>
        </el-form-item>
        <el-form-item label="药房类型" prop="pharmacyType">
          <el-select v-model="editForm.pharmacyType" placeholder="请选择">
            <el-option v-for="item in pharmacyTypes" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="location">
          <el-input v-model="editForm.location"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="editForm.contactPhone"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="editForm.manager"></el-input>
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <el-time-picker
              v-model="editForm.businessHours"
              is-range
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              :picker-options="{ selectableRange: '00:00:00-23:59:59' }"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status">
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 认</el-button>
      </div>
    </el-dialog>

    <!-- 新增弹框 -->
    <el-dialog
        title="新增药房"
        :visible.sync="addDialogVisible"
        width="500px"
        @close="resetAddForm"
    >
      <el-form :model="addForm" ref="addForm" label-width="100px" :rules="formRules">
        <el-form-item label="所属院区" prop="campusId">
          <el-select v-model="addForm.campusId" placeholder="请选择院区">
            <el-option
                v-for="item in campusList"
                :key="item.campusId"
                :label="item.campusName"
                :value="item.campusId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="药房名称" prop="pharmacyName">
          <el-input v-model="addForm.pharmacyName"></el-input>
        </el-form-item>
        <el-form-item label="药房类型" prop="pharmacyType">
          <el-select v-model="addForm.pharmacyType" placeholder="请选择">
            <el-option v-for="item in pharmacyTypes" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="location">
          <el-input v-model="addForm.location"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="addForm.contactPhone"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="addForm.manager"></el-input>
        </el-form-item>
        <el-form-item label="营业时间" prop="businessHours">
          <el-time-picker
              v-model="addForm.businessHours"
              is-range
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              :picker-options="{ selectableRange: '00:00:00-23:59:59' }"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status">
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { debounce } from 'lodash'

export default {
  name: 'PharmacyManage',
  data() {
    return {
      searchForm: {
        pharmacyType: '',
        status: '',
        dateRange: [],
      },
      pharmacyTypes: [],
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      editDialogVisible: false,
      editForm: {
        pharmacyId: '',
        campusId: '',
        pharmacyName: '',
        pharmacyType: '',
        location: '',
        contactPhone: '',
        manager: '',
        businessHours: [],
        status: 1
      },
      campusList: [],
      addDialogVisible: false,
      addForm: {
        pharmacyId: '',
        campusId: '',
        pharmacyName: '',
        pharmacyType: '',
        location: '',
        contactPhone: '',
        manager: '',
        businessHours: [],
        status: 1
      },
      formRules: {
        campusId: [
          { required: true, message: '请选择所属院区', trigger: 'change' }
        ],
        pharmacyName: [
          { required: true, message: '请输入药房名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        pharmacyType: [
          { required: true, message: '请选择药房类型', trigger: 'change' }
        ],
        location: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入负责人', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        businessHours: [
          { required: true, message: '请选择营业时间', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (value && value.length === 2) {
                const [start, end] = value;
                if (start >= end) {
                  callback(new Error('结束时间必须晚于开始时间'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
    }
  },
  methods: {
    fetchPharmacyTypes() {
      axios.get('/pharmacies/types').then(res => {
        this.pharmacyTypes = res.data || []
      })
    },
    fetchCampusList() {
      axios.get('/campuses/list', {
        params: {
          pageNum: 1,
          pageSize: 1000 // 假设院区不会太多，取足够大即可
        }
      }).then(res => {
        this.campusList = (res.data && res.data.records) ? res.data.records : []
      })
    },
    fetchTableData() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        pharmacyType: this.searchForm.pharmacyType,
        status: this.searchForm.status,
      }
      if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
        params.startTime = this.formatDateTimeForQuery(this.searchForm.dateRange[0])
        params.endTime = this.formatDateTimeForQuery(this.searchForm.dateRange[1])
      }
      axios.get('/pharmacies/list', { params }).then(res => {
        const records = res.data.records || []
        this.tableData = records.map((item, idx) => {
          const campus = this.campusList.find(c => c.campusId === item.campusId)
          return {
            ...item,
            campusName: campus ? campus.campusName : '',
            index: (this.pageNum - 1) * this.pageSize + idx + 1,
          }
        })
        this.total = res.data.total || 0
      })
    },
    handleSearch() {
      this.pageNum = 1
      this.fetchTableData()
    },
    handleAdd() {
      this.addForm = {
        pharmacyId: '',
        campusId: '',
        pharmacyName: '',
        pharmacyType: '',
        location: '',
        contactPhone: '',
        manager: '',
        businessHours: [],
        status: 1
      }
      this.addDialogVisible = true
    },
    handleEdit(row) {
      this.editForm = Object.assign({}, row)
      if (row.businessHours && row.businessHours.includes('-')) {
        this.editForm.businessHours = row.businessHours.split('-')
      } else {
        this.editForm.businessHours = []
      }
      this.editDialogVisible = true
    },
    handleChangeStatus(row, status) {
      this.$confirm(
          `确定要${status === 1 ? '启用' : '停用'}该药房吗？`,
          '提示',
          { type: 'warning' }
      ).then(() => {
        axios.post('/pharmacies/status', null, {
          params: {
            pharmacyId: row.pharmacyId,
            status,
          },
        }).then(() => {
          this.$message.success('操作成功')
          this.fetchTableData()
        })
      })
    },
    handlePageChange(val) {
      this.pageNum = val
      this.fetchTableData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.pageNum = 1
      this.fetchTableData()
    },
    submitEditForm() {
      this.$refs.editForm.validate(valid => {
        if (!valid) return
        if (Array.isArray(this.editForm.businessHours) && this.editForm.businessHours.length === 2) {
          this.editForm.businessHours = `${this.editForm.businessHours[0]}-${this.editForm.businessHours[1]}`
        }
        axios.post('/pharmacies/edit', this.editForm).then(res => {
          this.$message.success('修改成功')
          this.editDialogVisible = false
          this.fetchTableData()
        })
      })
    },
    formatDateTime(val) {
      if (!val) return ''
      const date = new Date(val)
      if (isNaN(date.getTime())) return val
      const y = date.getFullYear()
      const m = ('0' + (date.getMonth() + 1)).slice(-2)
      const d = ('0' + date.getDate()).slice(-2)
      const h = ('0' + date.getHours()).slice(-2)
      const min = ('0' + date.getMinutes()).slice(-2)
      const s = ('0' + date.getSeconds()).slice(-2)
      return `${y}-${m}-${d} ${h}:${min}:${s}`
    },
    formatDateTimeForQuery(date) {
      if (!date) return ''
      const d = new Date(date)
      const y = d.getFullYear()
      const m = ('0' + (d.getMonth() + 1)).slice(-2)
      const day = ('0' + d.getDate()).slice(-2)
      const h = ('0' + d.getHours()).slice(-2)
      const min = ('0' + d.getMinutes()).slice(-2)
      const s = ('0' + d.getSeconds()).slice(-2)
      return `${y}-${m}-${day} ${h}:${min}:${s}`
    },
    submitAddForm() {
      this.$refs.addForm.validate(valid => {
        if (!valid) return
        if (Array.isArray(this.addForm.businessHours) && this.addForm.businessHours.length === 2) {
          this.addForm.businessHours = `${this.addForm.businessHours[0]}-${this.addForm.businessHours[1]}`
        }
        axios.post('/pharmacies/add', this.addForm).then(res => {
          this.$message.success('新增成功')
          this.addDialogVisible = false
          this.fetchTableData()
        })
      })
    },
    // 重置新增表单
    resetAddForm() {
      this.addForm = {
        pharmacyId: '',
        campusId: '',
        pharmacyName: '',
        pharmacyType: '',
        location: '',
        contactPhone: '',
        manager: '',
        businessHours: [],
        status: 1
      }
      // 重置表单验证状态
      if (this.$refs.addForm) {
        this.$refs.addForm.resetFields()
      }
    },
  },
  mounted() {
    this.fetchCampusList()
    this.fetchPharmacyTypes()
    this.fetchTableData()
    this.debouncedFetchData = debounce(() => {
      this.pageNum = 1
      this.fetchTableData()
    }, 400)
  },
}
</script>

<style scoped>
.pharmacy-manage {
  padding: 24px;
  background: #fff;
  border-radius: 6px;
}
.filter-form {
  margin-bottom: 12px;
}
.pagination-wrapper {
  margin-top: 16px;
  text-align: right;
}
.status-enabled {
  color: #52c41a;
  font-weight: bold;
}
.status-disabled {
  color: #ff7875;
  font-weight: bold;
}
</style>